﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using FingerPrint.WebUI.Models;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace FingerPrint.WebUI.DAL
{
    public class FingerPrintContext : DbContext
    {
        // Link dataset to Database table
        public DbSet<SalesOrder> SalesOrders { get; set; }
        public DbSet<Employee> Employees { get; set; }
        public DbSet<Department> Departments { get; set; }
        public DbSet<Contact> Contacts { get; set; }
        public DbSet<Customer> Customers { get; set; }
        public DbSet<Product> Products { get; set; }
        public DbSet<ProductGroup> ProductGroups { get; set; }
        public DbSet<ProductCategory> ProductCategories { get; set; }
        public DbSet<UserProfile> UserProfiles { get; set; }

        // OnModelCreating method specify the relationships
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            // configure zero-or-one-to-many relationship between the SalesOrder and Employee entities
            modelBuilder.Entity<SalesOrder>()
                .HasOptional(p => p.Employee);

            // configure many-to-many relationship between the SalesOrder and Product entities
            modelBuilder.Entity<SalesOrder>()
                .HasMany(c => c.Products)
                .WithMany(i => i.SaleOrders)
                .Map(t => t.MapLeftKey("SalesOrderID")
                    .MapRightKey("ProductID")
                    .ToTable("SalesOrderProduct", "Sales"));

            // May one to one relationship
            modelBuilder.Entity<Product>()
                .HasRequired(t => t.ProductGroup);

        }
    }
}
